package zhieasy.cn.xpu_helper.security.provider;

import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import zhieasy.cn.xpu_helper.security.detailservice.WechatDetailsService;
import zhieasy.cn.xpu_helper.security.token.WeChatAuthenticationToken;

/**
 * @author DaHang
 * @date 2020/8/14 16:20
 */
public class WechatAuthenticationProvider implements AuthenticationProvider {
    private WechatDetailsService wechatDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        WeChatAuthenticationToken smsCodeAuthenticationToken = (WeChatAuthenticationToken) authentication;
        UserDetails user = wechatDetailsService.loadUserByUsername((String)smsCodeAuthenticationToken.getPrincipal());

        if(user == null){
            throw new InternalAuthenticationServiceException("用户不存在");
        }

        WeChatAuthenticationToken authenticationResult = new WeChatAuthenticationToken(user,user.getAuthorities());
        authenticationResult.setDetails(smsCodeAuthenticationToken.getDetails());

        return authenticationResult;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return WeChatAuthenticationToken.class.isAssignableFrom(aClass);
    }

    public UserDetailsService getUserDetailsService() {
        return wechatDetailsService;
    }

    public void setUserDetailsService(WechatDetailsService wechatDetailsService) {
        this.wechatDetailsService = wechatDetailsService;
    }

}
